import wx
import wx.lib.agw.flatnotebook as fnb
import os
import json
from pathlib import Path

import config
from config import global_config

class ConfigDialog(wx.Dialog):
    def __init__(self, parent, title="配置"):
        super(ConfigDialog, self).__init__(parent, title=title, size=(600, 400))
        self.parent = parent
        self.config_path = os.path.join(str(Path.home()), ".aitrader", "config.json")


        self.init_ui()
        self.Centre()

    def init_ui(self):
        # 主面板
        panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        # 创建FlatNotebook（顶部标签页，无关闭按钮）
        style = fnb.FNB_NO_X_BUTTON | fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NODRAG
        self.notebook = fnb.FlatNotebook(panel, agwStyle=style)

        # 基本配置标签页
        basic_panel = wx.Panel(self.notebook)
        self.create_basic_panel(basic_panel)
        self.notebook.AddPage(basic_panel, "基本配置")

        # 用户配置标签页
        user_panel = wx.Panel(self.notebook)
        self.create_user_panel(user_panel)
        self.notebook.AddPage(user_panel, "用户管理")

        main_sizer.Add(self.notebook, 1, wx.EXPAND | wx.ALL, 5)

        # 底部按钮区域（水平排列，确定取消放在右侧）
        btn_panel = wx.Panel(panel)
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # 添加弹性空间将按钮推到右侧
        btn_sizer.AddStretchSpacer()

        ok_btn = wx.Button(btn_panel, wx.ID_OK, "确定")
        cancel_btn = wx.Button(btn_panel, wx.ID_CANCEL, "取消")

        btn_sizer.Add(ok_btn, 0, wx.RIGHT, 5)
        btn_sizer.Add(cancel_btn, 0)

        btn_panel.SetSizer(btn_sizer)
        main_sizer.Add(btn_panel, 0, wx.EXPAND | wx.ALL, 5)

        panel.SetSizer(main_sizer)

        # 绑定事件
        ok_btn.Bind(wx.EVT_BUTTON, self.on_ok)
        cancel_btn.Bind(wx.EVT_BUTTON, self.on_cancel)

    def create_basic_panel(self, panel):
        sizer = wx.GridBagSizer(5, 5)

        # 数据文件夹路径配置
        data_dir_label = wx.StaticText(panel, label="数据文件夹路径:")
        self.data_dir_text = wx.TextCtrl(panel,
                                         value=global_config.data_dir)
        browse_btn = wx.Button(panel, label="浏览...")

        sizer.Add(data_dir_label, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
        sizer.Add(self.data_dir_text, pos=(0, 1), span=(1, 2), flag=wx.EXPAND | wx.ALL, border=5)
        sizer.Add(browse_btn, pos=(0, 3), flag=wx.ALL, border=5)

        # 其他配置项可以在这里添加
        # ...

        sizer.AddGrowableCol(1)
        panel.SetSizer(sizer)

        # 绑定事件
        browse_btn.Bind(wx.EVT_BUTTON, self.on_browse)

    def create_user_panel(self, panel):
        sizer = wx.GridBagSizer(5, 5)

        # 用户Token配置
        token_label = wx.StaticText(panel, label="用户Token:")
        self.token_text = wx.TextCtrl(panel, value=global_config.user_token, style=wx.TE_PASSWORD)

        sizer.Add(token_label, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
        sizer.Add(self.token_text, pos=(0, 1), span=(1, 3), flag=wx.EXPAND | wx.ALL, border=5)

        # 登录按钮
        login_btn = wx.Button(panel, label="登录")
        sizer.Add(login_btn, pos=(1, 0), span=(1, 4), flag=wx.EXPAND | wx.ALL, border=5)

        # 用户信息显示
        self.user_info_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY)
        sizer.Add(self.user_info_text, pos=(2, 0), span=(1, 4), flag=wx.EXPAND | wx.ALL, border=5)

        sizer.AddGrowableRow(2)
        sizer.AddGrowableCol(1)
        panel.SetSizer(sizer)

        # 绑定事件
        login_btn.Bind(wx.EVT_BUTTON, self.on_login)

    def on_browse(self, event):
        default_path = self.data_dir_text.GetValue()
        dlg = wx.DirDialog(self, "选择数据文件夹", defaultPath=default_path)

        if dlg.ShowModal() == wx.ID_OK:
            self.data_dir_text.SetValue(dlg.GetPath())
        dlg.Destroy()

    def on_login(self, event):
        token = self.token_text.GetValue()
        if not token:
            wx.MessageBox("请输入Token", "错误", wx.OK | wx.ICON_ERROR)
            return

        # 这里模拟API调用
        wx.BeginBusyCursor()
        try:
            # 模拟API调用延迟
            #wx.MilliSleep(1000)
            from common.api import login

            # 这里应该是实际的API调用代码
            data,status_code = login(token)
            if status_code == 200:
                self.user_info_text.SetValue(json.dumps(data, indent=2, ensure_ascii=False))
                wx.MessageBox("登录成功", "提示", wx.OK | wx.ICON_INFORMATION)



            else:
                wx.MessageBox("登录失败: " + data.get("message", "未知错误"), "错误", wx.OK | wx.ICON_ERROR)
        except Exception as e:
            wx.MessageBox(f"API调用失败: {str(e)}", "错误", wx.OK | wx.ICON_ERROR)
        finally:
            wx.EndBusyCursor()

    def on_ok(self, event):

        try:
            global_config.data_dir = self.data_dir_text.GetValue()
            global_config.user_token = self.token_text.GetValue()
            global_config.to_toml(str(config.config_file.resolve()))
        except Exception as e:
            print(f"保存配置失败: {e}")



        self.EndModal(wx.ID_OK)

    def on_cancel(self, event):
        self.EndModal(wx.ID_CANCEL)



